package com.imay.live.activity.family;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.imay.live.R;
import com.imay.live.activity.BaseRequestActivity;
import com.imay.live.activity.RoomLiveShortActivity;
import com.imay.live.activity.family.controller.FamilyHomeController;
import com.imay.live.activity.family.helper.session.SessionHelper;
import com.imay.live.activity.family.manager.FamilyUserChangeManager;
import com.imay.live.manager.AccountManager;
import com.imay.live.manager.FamilyAccountManager;
import com.imay.live.model.FamilyModel;
import com.imay.live.model.FamilyUserInfo;
import com.imay.live.model.FamilyUserModel;
import com.imay.live.model.FeedModel;
import com.imay.live.model.MenuItemModel;
import com.imay.live.model.RankingModel;
import com.imay.live.model.RoomInfoModel;
import com.imay.live.model.ShortLiveInfoModel;
import com.imay.live.model.UserInfoModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.proto.helper.ProtoRequestParams;
import com.imay.live.utils.PermissionUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.dialog.ChoiseDialogFragment;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.netease.nim.uikit.contact.core.item.ItemTypes;
import com.netease.nim.uikit.contact.core.model.ContactDataAdapter;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.team.TeamService;
import com.netease.nimlib.sdk.team.constant.TeamTypeEnum;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * Created by Administrator on 2017/8/30 0030.
 */

public class FamilyHomeActivity extends BaseRequestActivity implements View.OnClickListener, FamilyUserChangeManager.FamilyUserChangeListener {

    public static final String KEY_STATUS = "key_status";
    public static final String KEY_FAMILY = "key_family";

    private String requestFamilyLeaveCommand, loadLiveFamilyCommand,
            loadFamilyFeedCommand, loadFamilySupperLiveCommand, requestFamilyUserCommand, loadFamilyRankCommand;

    public static final int OTHERS = 1;
    public static final int ME = 2;

    private FamilyHomeController controller;

    private int status;

    private FamilyUserChangeManager manager;

    private FamilyModel familyModel;

    private int count = 3;
    private ArrayList<Long> shortLiveIds;

    /**
     * 家族首页
     *
     * @param context
     */
    public static void startActivity(Context context, int status) {
        Intent intent = new Intent(context, FamilyHomeActivity.class);
        intent.putExtra(KEY_STATUS, status);
        context.startActivity(intent);
    }

    /**
     * 家族首页并清除之前的
     *
     * @param context
     * @param status
     */
    public static void startActivitySingleTop(Context context, int status) {
        Intent intent = new Intent(context, FamilyHomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(KEY_STATUS, status);
        context.startActivity(intent);
    }

    /**
     * 家族首页
     *
     * @param context
     * @param status
     * @param familyModel
     */
    public static void startActivity(Context context, int status, FamilyModel familyModel) {
        Intent intent = new Intent(context, FamilyHomeActivity.class);
        intent.putExtra(KEY_STATUS, status);
        intent.putExtra(KEY_FAMILY, familyModel);
        context.startActivity(intent);
    }

    @Override
    protected boolean useDynamicTitleBar() {
        return false;
    }

    @Override
    protected boolean isTranslucentStatus() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_family_home;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        status = getIntent().getIntExtra(KEY_STATUS, OTHERS);
        familyModel = (FamilyModel) getIntent().getSerializableExtra(KEY_FAMILY);
        /*if (FamilyAccountManager.getInstance().isHasFamilyInfo() && familyModel != null) {
            FamilyUserInfo familyUserInfo = FamilyAccountManager.getInstance().getFamilyUserInfo();
            if (familyUserInfo.getFamily().getId() == familyModel.getId()) {
                status = ME;
            }
        }*/
        controller = (FamilyHomeController) FamilyHomeController.Builder.create(this, FamilyHomeController.class).build();
        controller.setViewHight(getStatusBarHeight());
        if (status == OTHERS) {
            controller.setOtherViewHide();
            controller.setTitleData(familyModel);
        } else if (status == ME) {
            FamilyUserInfo familyUserInfo = FamilyAccountManager.getInstance().getFamilyUserInfo();
            familyModel = familyUserInfo.getFamily();
            controller.setMeView();
            controller.setTitleData(familyModel);
        }

        manager = FamilyUserChangeManager.Builder.create(this).build();

        controller.setRresh(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                if (!FamilyAccountManager.isLocked(familyModel.getBeLocked())) {
                    if (status == ME) {
                        FamilyUserInfo familyUserInfo = FamilyAccountManager.getInstance().getFamilyUserInfo();
                        familyModel = familyUserInfo.getFamily();
                        controller.setTitleData(familyModel);
                    }
                    loadLiveFamily();
                    loadFamilyFeed(0);
                    loadFamilySupperLive(0);
                    loadFamilyUsers();
                    loadFamilyRank();
                    controller.refreshUnreadView();
                }

                controller.finishRresh();
            }
        });

        shortLiveIds = new ArrayList<Long>();

        if (!FamilyAccountManager.isLocked(familyModel.getBeLocked())) {
            loadLiveFamily();
            loadFamilyFeed(1);
            loadFamilySupperLive(1);
            loadFamilyUsers();
            loadFamilyRank();
            registerObservers(true);
        } else {
            controller.setFeedCount(0);
            controller.setShortLiveCount(0);
            controller.setLiveCount(0);
            controller.setLockedRefreshView();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (status == ME) {
            getMenuInflater().inflate(R.menu.menu_main, menu);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_menu) {
            FamilyUserInfo familyUserInfo = FamilyAccountManager.getInstance().getFamilyUserInfo();
            if (familyUserInfo != null && familyUserInfo.getFamilyUser() != null) {
                int admin = familyUserInfo.getFamilyUser().getAdmin();
                controller.initMenu(admin, new ChoiseDialogFragment.OnItemClickListener() {
                    @Override
                    public void itemClick(int tagCallBack, int position, MenuItemModel str) {
                        switch (str.getAction()) {
                            case FamilyHomeController.MENU_ACTION_FAMILY_MODIFY:
                                FamilyCreateActivity.startActivity(FamilyHomeActivity.this, FamilyCreateActivity.MODIFY);
                                break;
                            case FamilyHomeController.MENU_ACTION_FAMILY_JOIN:
                                FamilyAcceptActivity.startActivity(FamilyHomeActivity.this, familyModel.getId());
                                break;
                            case FamilyHomeController.MENU_ACTION_FAMILY_OUT:
                                requestQuitFamily();
                                break;
                        }
                    }
                });
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fiv_family_person:
                if (FamilyAccountManager.isLocked(familyModel.getBeLocked())) {
                    ToastUtil.show(FamilyHomeActivity.this, R.string.str_family_locked);
                    return;
                }
                FamilyPersonActivity.startActivity(FamilyHomeActivity.this, familyModel.getId(), familyModel.getDesignation(), status);
                break;
            case R.id.tv_family_apply:
                if (FamilyAccountManager.isLocked(familyModel.getBeLocked())) {
                    ToastUtil.show(FamilyHomeActivity.this, R.string.str_family_locked_other);
                    return;
                }
                if (FamilyAccountManager.getInstance().isHasFamilyInfo()) {
                    ToastUtil.show(FamilyHomeActivity.this, R.string.str_family_apply_note);
                    return;
                }
                FamilyJoinActivity.startActivity(FamilyHomeActivity.this, familyModel.getId());
                break;
            case R.id.ll_family_im:
                if (status == OTHERS) {
                    return;
                }
                if (FamilyAccountManager.isLocked(familyModel.getBeLocked())) {
                    ToastUtil.show(FamilyHomeActivity.this, R.string.str_family_locked);
                    return;
                }
                SessionHelper.startTeamSession(FamilyHomeActivity.this, familyModel.getTid());
                break;
            case R.id.fiv_family_lives:
                if (status == OTHERS) {
                    return;
                }
                if (FamilyAccountManager.isLocked(familyModel.getBeLocked())) {
                    ToastUtil.show(FamilyHomeActivity.this, R.string.str_family_locked);
                    return;
                }
                FamilyLiveActivity.startActivity(FamilyHomeActivity.this, familyModel.getId());
                break;
            case R.id.rl_family_home_title:
                if (FamilyAccountManager.isLocked(familyModel.getBeLocked())) {
                    ToastUtil.show(FamilyHomeActivity.this, R.string.str_family_locked);
                    return;
                }
                FamilyModel mFamilyModel = familyModel;
                if (status == ME) {
                    FamilyAccountManager.getInstance().loadFamilyUserInfo(false);
                    if (FamilyAccountManager.getInstance().isHasFamilyInfo()) {
                        mFamilyModel = FamilyAccountManager.getInstance().getFamilyUserInfo().getFamily();
                    }
                }
                FamilyLevelActivity.startActivity(FamilyHomeActivity.this, mFamilyModel);
                break;
            case R.id.fiv_family_dynamics:
                if (status == OTHERS) {
                    return;
                }
                if (FamilyAccountManager.isLocked(familyModel.getBeLocked())) {
                    ToastUtil.show(FamilyHomeActivity.this, R.string.str_family_locked);
                    return;
                }
                controller.setFeedCount(0);
                FamilyFeedActivity.startActivity(FamilyHomeActivity.this, familyModel.getId());
                break;
            case R.id.fiv_family_super:
                if (status == OTHERS) {
                    return;
                }
                if (FamilyAccountManager.isLocked(familyModel.getBeLocked())) {
                    ToastUtil.show(FamilyHomeActivity.this, R.string.str_family_locked);
                    return;
                }
                controller.setShortLiveCount(0);
                RoomLiveShortActivity.startActivityforFamily(FamilyHomeActivity.this, shortLiveIds, familyModel.getId());
                break;
            case R.id.fiv_family_con:
                if (status == OTHERS) {
                    return;
                }
                if (FamilyAccountManager.isLocked(familyModel.getBeLocked())) {
                    ToastUtil.show(FamilyHomeActivity.this, R.string.str_family_locked);
                    return;
                }
                //FamilySettingActivity.startActivity(FamilyHomeActivity.this);
                FamilyRankActivity.startActivity(FamilyHomeActivity.this, familyModel.getId());
                break;
        }
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        super.onRequestSuccess(command, data);
        if (command.equals(requestFamilyLeaveCommand)) {
            Result<String> resp = JSONObject.parseObject(data, new TypeReference<Result<String>>() {
            }.getType());
            if (resp.result == CodeSuccess) {
                ToastUtil.show(this, R.string.str_family_out_success);
                String account = FamilyAccountManager.getAccount();
                if (!TextUtils.isEmpty(account)) {
                    NIMClient.getService(MsgService.class).clearUnreadCount(account, SessionTypeEnum.Team);
                }
                FamilyAccountManager.getInstance().clear();
                finish();
            }
        } else if (command.equals(loadLiveFamilyCommand)) {
            Result<JSONObject> result = JSON.parseObject(data, new TypeReference<Result<JSONObject>>() {
            }.getType());
            if (result.data.containsKey("roomCount") && result.data.containsKey("rooms")) {
                List<RoomInfoModel> liveData = JSON.parseObject(result.data.getString("rooms"), new TypeReference<List<RoomInfoModel>>() {
                }.getType());
                controller.setLiveData(liveData);
                if (status == OTHERS) {
                    controller.setLiveItemClick(liveData);
                } else if (status == ME) {
                    controller.setLiveCount(result.data.getIntValue("roomCount"));
                }
            }
        } else if (command.equals(loadFamilyFeedCommand)) {
            Result<JSONObject> result = JSON.parseObject(data, new TypeReference<Result<JSONObject>>() {
            }.getType());
            if (result.data.containsKey("feeds")) {
                ArrayList<FeedModel> feedModels = JSON.parseObject(result.data.getString("feeds"), new TypeReference<ArrayList<FeedModel>>() {
                }.getType());
                controller.setFeedData(feedModels);
            }
            if (result.data.containsKey("unread")) {
                int unread = result.data.getInteger("unread");
                controller.setFeedCount(unread);
            }
        } else if (command.equals(loadFamilySupperLiveCommand)) {
            Result<JSONObject> result = JSON.parseObject(data, new TypeReference<Result<JSONObject>>() {
            }.getType());
            if (result.data.containsKey("shortLives")) {
                ArrayList<ShortLiveInfoModel> shortLiveInfoModels = JSON.parseObject(result.data.getString("shortLives"), new TypeReference<ArrayList<ShortLiveInfoModel>>() {
                }.getType());
                if (!shortLiveInfoModels.isEmpty()) {
                    shortLiveIds.add(shortLiveInfoModels.get(0).getShortLiveId());
                }
                controller.setShortLiveData(shortLiveInfoModels);
            }
            if (result.data.containsKey("unread")) {
                int unread = result.data.getInteger("unread");
                controller.setShortLiveCount(unread);
            }
        } else if (command.equals(requestFamilyUserCommand)) {
            Result<FamilyUserModel> result = JSON.parseObject(data, new TypeReference<Result<FamilyUserModel>>() {
            }.getType());
            controller.setUserData(result.data);
        } else if (command.equals(loadFamilyRankCommand)) {
            Result<JSONObject> result = JSON.parseObject(data, new TypeReference<Result<JSONObject>>() {
            }.getType());
            if (result.data.containsKey("ranks")) {
                ArrayList<RankingModel> rankingModels = JSON.parseObject(result.data.getString("ranks"), new TypeReference<ArrayList<RankingModel>>() {
                }.getType());
                controller.setRankData(rankingModels);
            }
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        super.onRequestError(command, code, message);
        ErrorResult.toastError(this, code);
    }

    private void loadLiveFamily() {
        loadLiveFamilyCommand = ProtoRequestHelper.task(ProtoHttpFactory.getFamilyLive(familyModel.getId(), 0, count)).setTag(this.hashCode()).request(this);
    }

    private void loadFamilyFeed(int first) {
        loadFamilyFeedCommand = ProtoRequestHelper.task(ProtoHttpFactory.getFamilyFeed(familyModel.getId(), 0, count, first)).setTag(this.hashCode()).request(this);
    }

    private void loadFamilySupperLive(int first) {
        loadFamilySupperLiveCommand = ProtoRequestHelper.task(ProtoHttpFactory.getFamilySupperLive(familyModel.getId(), 0, count, first)).setTag(this.hashCode()).request(this);
    }

    private void loadFamilyUsers() {
        requestFamilyUserCommand = ProtoRequestHelper.task(ProtoHttpFactory.getFamilyUsers(familyModel.getId(), 0, count)).setTag(this.hashCode()).request(this);
    }

    private void requestQuitFamily() {
        requestFamilyLeaveCommand = ProtoRequestHelper.task(ProtoHttpFactory.familyLeave()).setTag(this.hashCode()).request(this);
    }

    private void loadFamilyRank() {
        loadFamilyRankCommand = ProtoRequestHelper.task(ProtoHttpFactory.getFamilyRank(familyModel.getId(), "total", 0, count)).setTag(this.hashCode()).request(this);
    }

    @Override
    protected void onDestroy() {
        registerObservers(false);
        controller.onPause();
        manager.unregisterFamilyNotify();
        super.onDestroy();

    }


    @Override
    public void elderChange() {
        loadFamilyUsers();
    }

    @Override
    public void userRefresh() {
        loadFamilyUsers();
    }


    private void registerObservers(boolean register) {
        MsgServiceObserve service = NIMClient.getService(MsgServiceObserve.class);
        service.observeRecentContact(messageObserver, register);
        service.observeRecentContactDeleted(deleteObserver, register);
    }

    Observer<List<RecentContact>> messageObserver = new Observer<List<RecentContact>>() {
        @Override
        public void onEvent(List<RecentContact> recentContacts) {
            controller.refreshUnreadView();
        }
    };

    Observer<RecentContact> deleteObserver = new Observer<RecentContact>() {
        @Override
        public void onEvent(RecentContact recentContact) {
            controller.refreshUnreadView();

        }
    };


}
